package filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CharsetFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取配置文件信息，初始化配置
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //写过滤器的业务
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String url = request.getRequestURI();
        String[] arry={".html",".css",".js",".jpg",".png"};
        Boolean flag = true;
        url = url.substring(url.lastIndexOf("/")+1,url.length());
        for (int i=0;i<arry.length;i++){
            if ((url.indexOf(arry[i])>-1)){
                flag = false;
            }
        }
        if (flag&&!url.equals("")){
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("application/json;charset:utf-8");
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        //清除某些配置
    }
}
